const app = getApp();
const { isAdminRole } = require('../../../api/common');

Page({
  data: {
    msgList: [],
    current: 0,
    tabs: ['留言对话', '待回复'],
    page: '2', // 接口标明string
    isPoster: false,
    isMsgList: false,
    isCard: false,
    loading: true,
    isWXWork: app.isWXWork,
    isData: false,
    imgUrl: app.imgUrl + 'abnor-23.png',
    keyword: '',
    isEmpty: true,
  },
 
  onLoad(options) {
    let { isPoster, isCard } = options;
    let openid = wx.getStorageSync('wsOpenID') || wx.getStorageSync('OPENID');
    if (isPoster) {
      wx.setNavigationBarTitle({ title: '海报' });
      return this.setData({ isPoster: true });
    }
    this.setData({ openid });
    if (isCard) {
      let { cardid } = options;
      wx.setNavigationBarTitle({ title: '保存名片' });
      this.onCreateThumb(cardid);
      return this.setData({ isCard: true });
    }
    this.setData({ isMsgList: true });
    app.v8_card_action_log = [];
  },
  async onShow() {
    const isAdmin = await isAdminRole();
    this.setData({
      isAdmin
    })

    this.getMsgList({
      page: '1',
    }).then(res => {
      if (res.length > 0) {
        this.setData({
          msgList: res,
        });
      }
    });
  },
  search() {
    let that = this;
    that.getMsgList({ page: '1' }).then(res => {
      wx.stopPullDownRefresh();
      if (res.length > 0) {
        that.setData({
          msgList: res,
          page: '2',
        });
      } else {
        that.setData({
          msgList: [],
          page: '1',
        });
      }
    });
  },
  clearTxt() {
    this.setData({
      keyword: '',
      page: 1,
      isEmpty: true,
    }, () => {
      this.search();
    });
  },

  onInput(e) {
    let val = e.detail.value;
    if (val.trim()) {
      this.setData({
        isEmpty: false,
      });
    } else {
      this.setData({
        isEmpty: true,
      });
    }
    this.setData({
      keyword: e.detail.value,
    });
  },
  onTabs(e) {
    const { current } = e.currentTarget.dataset;
    let that = this;
    this.setData(
      {
        current: current,
        isData: false,
      },
      () => {
        this.getMsgList({ page: '1' }).then(res => {
          wx.stopPullDownRefresh();
          if (res.length > 0) {
            that.setData({
              msgList: res,
              page: '2',
            });
          } else {
            that.setData({
              msgList: [],
              page: '1',
            });
          }
        });
      },
    );
  },
  toDetail(e) {
    let { url, ...params } = e.currentTarget.dataset;
    url && app.util.navigateTo(url, params);
  },
  onUnload() {
    let data = app.v8_card_action_log;
    data instanceof Array &&
      data.length > 0 &&
      app.util.statRequest({
        pt: getCurrentPages().pop().route,
        pm: JSON.stringify(getCurrentPages().pop().options),
        tm: 0,
        cn: 'click',
        tp: 2,
        aa: JSON.stringify(data),
      });
    app.v8_card_action_log = [];
  },

  onCreateThumb: function(card_id) {
    let that = this;
    let openid = this.data.openid;
    let qr_path = 'common/component/universal-card/card-show';
    let module = app.siteInfo.module;
    let params = {
      card_id,
      openid,
      qr_path,
    };
    if (module === 'ws_micro_shop') {
      params.sid = app.ws_micro_shop_globalData.shopid;
    }
    this.setData({
      showLoading: true,
    });
    wx.showLoading({
      title: '生成名片海报中..',
      mask: false,
    });

    app.util.request({
      url: 'card/api/create_poster',
      data: params,
      success: function(res) {
        if (res.data.errno === 0) {
          let qrCode = res.data.data.img_url;
          that.setData({
            qrCode,
            showLoading: false,
          });
          wx.hideLoading();
        }
      },
      fail: function() {
        wx.hideLoading();
        wx.showToast({
          title: '生成海报失败，退出重试',
          icon: 'none',
        });
      },
    });
  },

  onPullDownRefresh: function() {
    let that = this;
    if (!this.data.isMsgList) {
      wx.stopPullDownRefresh();
    } else {
      this.getMsgList({
        page: '1',
      })
        .then(res => {
          wx.stopPullDownRefresh();
          // && res[0].id !== msgList[0].id，可能last_content有更新过，需要重新合并。
          if (res.length > 0) {
            that.setData({
              msgList: res,
              page: '2',
            });
          } else {
            wx.showToast({
              title: '没有新会话',
              icon: 'none',
            });
          }
        })
        .catch(e => {
          wx.stopPullDownRefresh();
          wx.showToast({
            title: '没有新会话',
            icon: 'none',
          });
        });
    }
  },

  onLoadMore: function() {
    let that = this;
    let { msgList, page } = this.data;

    this.setData({
      isLoading: true,
    });
    this.getMsgList({})
      .then(res => {
        if (res.length > 0) {
          that.setData({
            msgList: [...msgList, ...res],
            page: Number(page) + 1,
          });
        } else {
          // wx.showToast({
          //   title: '没有更多了',
          //   icon: 'none',
          // });
        }
        that.setData({
          isLoading: false,
        });
      })
      .catch(e => {
        // wx.showToast({
        //   title: '没有更多了',
        //   icon: 'none',
        // });
        that.setData({
          isLoading: false,
        });
      });
  },

  // 获取留言列表数据
  getMsgList(obj = {}) {
    let that = this;
    let channel;
    let { current, openid, page, keyword, isAdmin } = this.data;
    if (obj.page) page = obj.page;
    wx.showLoading({ title: '请稍候' });
    
    let data = {
      openid,
      page,
      pagesize: '15',
      bindacid: wx.getStorageSync('cor_uniacid') || 0,
    };
    if (Number(current) === 0){
      // data.channel = 1;
      if (isAdmin) {
        data.channel = 1;
      } else {
        data.channel = 0;
      }
    } else {
      data.channel = 0;
    }
    if (keyword) data.keyword = keyword;
    return new Promise((resolve, reject) => {
      app.util.request({
        url: 'message/api/getJpListNew',
        data,
        success: function(res) {
          if (Number(res.data.errno) === 0) resolve(res.data.data);
          else reject(new Error(false));
        },
        fail: function(err) {
          reject(err);
        },
        complete: function() {
          wx.hideLoading();
            that.setData({ loading: false, isData: true });
        },
      });
    });
  },

  gotoMsg(e) {
    // 此处fromOpenid 第一次发起会话的人；
    // to_openid，被动发起会话的人；’
    // 跳转到message对话页，语义上需要转成 fromOpenid: 发消息者 toopneid: 消息接收者
    let guestMobile = this.data.guestMobile;
    if (!guestMobile && !this.data.isWXWork) {
      this.checkUserTelephone.call(this, e);
    } else {
      let { mid, toOpenid, fromOpenid } = e.currentTarget.dataset;
      let currenUserOpenID = this.data.openid; // 传给message页的openID应该是当前用户的openid
      if (currenUserOpenID === fromOpenid) fromOpenid = toOpenid;

      // TODO, 处理列表未读数据 m_id
      this.clearUMsg(mid);
      let url =
        '/common/component/universal-card/pages/message?openid=' +
        currenUserOpenID +
        '&m_id=' +
        mid +
        '&to_openid=' +
        fromOpenid +
        '&scene=inner';
      url += '&guestMobile=' + guestMobile;
      app.util.navigateTo(url);
    }
  },

  saveQrShow: function(argument) {
    let url = this.data.qrCode;
    url &&
      wx.downloadFile({
        url,
        success: function(res) {
          if (res.statusCode === 200) {
            let filePath = res.tempFilePath;
            wx.saveImageToPhotosAlbum({
              filePath,
              success: function(res) {
                wx.showToast({
                  title: '保存成功',
                  duration: 1500,
                  icon: 'success',
                });
                app.v8_card_action_log.push({ name: 'saveQrShow', result: true });
                setTimeout(function() {
                  wx.navigateBack({
                    delta: 1,
                  });
                }, 1500);
              },
              fail: function() {
                app.v8_card_action_log.push({ name: 'saveQrShow', result: false });
              },
            });
          }
        },
      });
  },

  clearUMsg: function(mid) {
    // let clickedMsgIndex;
    let that = this;
    this.data.msgList.forEach((item, index) => {
      if (Number(item.id) === Number(mid)) {
        let tmpKey = `msgList[${index}].n_see`;
        that.setData({
          [tmpKey]: '0',
        });
      }
    });
  },

  getUserMobile(e) {
    this.setData({ guestMobile: e.detail.mobile || '' });
  },
});
